package util

import (
	"os"
	"runtime"
	"time"

	"gitee.com/konyshe/gogo"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
)

var (
	pHealthMonitor *Monitor
)

func InitHealth() {
	pHealthMonitor = NewMonitor()
}

func HealthNet() map[string]float32 {
	d := make(map[string]float32)
	d["down"] = pHealthMonitor.GetDown()
	d["up"] = pHealthMonitor.GetUp()
	pHealthMonitor.Reset()

	return d
}

func HealthMemory() map[string]uint32 {
	v, _ := mem.VirtualMemory()

	// almost every return value is a struct
	//gogo.LogDebugF("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)

	d := make(map[string]uint32)
	d["total"] = uint32(v.Total)
	d["used"] = uint32(v.Used)
	d["available"] = uint32(v.Available)
	d["used_percent"] = uint32(v.UsedPercent)

	return d
}

func HealthCPU() map[string]uint32 {
	percpu := false
	numcpu := runtime.NumCPU()
	d := make(map[string]uint32)

	if runtime.GOOS != "windows" {
		v, err := cpu.Percent(time.Millisecond, percpu)
		if err != nil {
			gogo.LogErrorF("error %v", err)
		}
		// Skip CircleCI which CPU num is different
		if os.Getenv("CIRCLECI") != "true" {
			if (percpu && len(v) != numcpu) || (!percpu && len(v) != 1) {
				gogo.LogInfoF("wrong number of entries from CPUPercent: %v", v)
			}
		}
	}
	duration := time.Duration(5) * time.Microsecond
	v, err := cpu.Percent(duration, percpu)
	if err == nil {
		d["cpu_num"] = uint32(numcpu)
		d["used_percent"] = uint32(v[0])
	}

	return d
}
